<?php
namespace app\msgapi\service;

use app\msgapi\model\HuihuaGroup;
use think\facade\Log;

error_reporting(E_ERROR | E_PARSE);
class HuihuaGroupService
{

    /**存档数据处理写入group表中
     */
    public function saveGroupData($msgInfo){
        //判断当前数据组是否存在
        if($msgInfo['action'] == 'switch') return 0; //过滤掉切换企业数据
        if ($msgInfo['roomid'] != '') {
            $groupInfo = HuihuaGroup::where('chatid', $msgInfo['roomid'])->findOrEmpty()->toArray();
        } else {
            $chatids = [
                $msgInfo['from'] . '##' . $msgInfo['tolist'][0],
                $msgInfo['tolist'][0] . '##' . $msgInfo['from']
            ];
            $groupInfo = HuihuaGroup::where('chatid', 'in', $chatids)->findOrEmpty()->toArray();
        }
        if (!$groupInfo) {
            $groupData = [
                'chatid' => $msgInfo['roomid'] ? : $chatids[0],
                'is_crowd' => $msgInfo['roomid'] ? 1 : 0,
                'userlist' => implode(',',array_merge($msgInfo['tolist'], [$msgInfo['from']])), //下方insertGetId不能走模型转换,这里需要手动转换字符串
                'update_time'=>date('Y-m-d H:i:s', $msgInfo['msgtime'] / 1000)
            ];
            $groupId = HuihuaGroup::insertGetId($groupData);
        } else {
            $groupData = [
                'update_time'=>date('Y-m-d H:i:s', $msgInfo['msgtime'] / 1000)
            ];
            if($msgInfo['roomid']){
                $groupData['userlist'] = array_merge($msgInfo['tolist'], [$msgInfo['from']]); //下方update走模型转换,这里不需要手动转
            }
            $groupId = $groupInfo['id'];
            HuihuaGroup::update($groupData,['id'=>$groupId]);
        }
        return $groupId;
    }


}